<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>预警监控</span>
        <el-button type="primary" :icon="Plus" @click="openAddDrawer">
          新增预警
        </el-button>
      </div>
    </template>

    <!-- 查询表单 -->
    <el-form inline :model="queryForm" class="query-form" style="margin-bottom: 20px;">
      <el-form-item label="区域">
        <el-select v-model="queryForm.area" placeholder="请选择区域">
          <el-option label="哈达湾" value="hadawan"></el-option>
          <el-option label="鸟岛" value="niaodao"></el-option>
          <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
          <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
          <el-option label="泉湾" value="quanwan"></el-option>
          <el-option label="黑马河口" value="heimahekou"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
            v-model="queryForm.date"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="warningList"
        border
        style="width: 100%; margin-bottom: 20px"
    >
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <!-- 区域显示转换 -->
      <el-table-column label="区域" align="center">
        <template #default="scope">{{ formatAreaName(scope.row.area) }}</template>
      </el-table-column>
      <el-table-column prop="date" label="采集日期" width="160" align="center"></el-table-column>
      <!-- 风险等级显示转换 -->
      <el-table-column label="风险等级" width="120" align="center">
        <template #default="scope">{{ formatWarnLevel(scope.row.warnLevel) }}</template>
      </el-table-column>
      <el-table-column prop="algalBloom" label="水华覆盖比例(%)" align="center"></el-table-column>
      <el-table-column prop="operationTime" label="操作时间" width="160" align="center"></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button :icon="View" circle plain type="primary" @click="handleView(scope.row)"></el-button>
          <el-button :icon="Edit" circle plain type="success" @click="handleEdit(scope.row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>

    <!-- 详情抽屉 -->
    <el-drawer v-model="detailDrawer" title="预警详情" direction="rtl" size="50%">
      <el-descriptions column="1" border>
        <el-descriptions-item label="ID">{{ currentWarning.id }}</el-descriptions-item>
        <el-descriptions-item label="区域">{{ formatAreaName(currentWarning.area) }}</el-descriptions-item>
        <el-descriptions-item label="采集日期">{{ currentWarning.date }}</el-descriptions-item>
        <!-- 风险等级详情显示转换 -->
        <el-descriptions-item label="风险等级">{{ formatWarnLevel(currentWarning.warnLevel) }}</el-descriptions-item>
        <el-descriptions-item label="水华覆盖比例">{{ currentWarning.algalBloom }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ currentWarning.operationTime }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 编辑抽屉 -->
    <el-drawer v-model="editDrawer" title="编辑预警" direction="rtl" size="50%">
      <el-form
          ref="editFormRef"
          :model="editFormData"
          :rules="rules"
          label-width="120px"
          size="large"
      >
        <el-form-item label="ID" prop="id">
          <el-input v-model="editFormData.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="区域" prop="area">
          <el-select v-model="editFormData.area" placeholder="请选择区域">
            <el-option label="哈达湾" value="hadawan"></el-option>
            <el-option label="鸟岛" value="niaodao"></el-option>
            <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
            <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
            <el-option label="泉湾" value="quanwan"></el-option>
            <el-option label="黑马河口" value="heimahekou"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集日期" prop="date">
          <el-date-picker
              v-model="editFormData.date"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择采集日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="风险等级" prop="warnLevel">
          <el-select v-model="editFormData.warnLevel" placeholder="请选择风险等级">
            <el-option label="正常事件" value="0"></el-option>
            <el-option label="一般事件" value="1"></el-option>
            <el-option label="较大事件" value="2"></el-option>
            <el-option label="重大事件" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="水华覆盖比例(%)" prop="algalBloom">
          <el-input v-model="editFormData.algalBloom" placeholder="请填写水华覆盖比例"></el-input>
        </el-form-item>
        <el-form-item label="操作时间" prop="operationTime">
          <el-date-picker
              v-model="editFormData.operationTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择操作时间"
              disabled
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpdate">保存</el-button>
          <el-button @click="editDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 新增抽屉 -->
    <el-drawer v-model="addDrawer" title="新增预警" direction="rtl" size="50%">
      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          size="large"
      >
        <el-form-item label="区域" prop="area">
          <el-select v-model="formData.area" placeholder="请选择区域">
            <el-option label="哈达湾" value="hadawan"></el-option>
            <el-option label="鸟岛" value="niaodao"></el-option>
            <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
            <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
            <el-option label="泉湾" value="quanwan"></el-option>
            <el-option label="黑马河口" value="heimahekou"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集日期" prop="date">
          <el-date-picker
              v-model="formData.date"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择采集日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="风险等级" prop="warnLevel">
          <el-select v-model="formData.warnLevel" placeholder="请选择风险等级">
            <el-option label="正常事件" value="0"></el-option>
            <el-option label="一般事件" value="1"></el-option>
            <el-option label="较大事件" value="2"></el-option>
            <el-option label="重大事件" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="水华覆盖比例(%)" prop="algalBloom">
          <el-input v-model="formData.algalBloom" placeholder="请填写水华覆盖比例"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="addDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Plus, View, Delete, Edit } from '@element-plus/icons-vue'
import { warningListService, warningSaveService, warningDeleteService, warningUpdateService } from '@/api/warning'
import { ElMessage, ElMessageBox } from 'element-plus'

// 区域拼音-汉字映射表
const areaMap = {
  hadawan: '哈达湾',
  niaodao: '鸟岛',
  buhahekouhaibeiqu: '布哈河口海北区',
  buhahekouhainanqu: '布哈河口海南区',
  quanwan: '泉湾',
  heimahekou: '黑马河口'
}

// 风险等级数字-汉字映射表
const warnLevelMap = {
  '0': '正常事件',
  '1': '一般事件',
  '2': '较大事件',
  '3': '重大事件'
}

// 风险等级汉字-数字反向映射表
const warnLevelReverseMap = {
  '正常事件': '0',
  '一般事件': '1',
  '较大事件': '2',
  '重大事件': '3'
}

// 拼音转汉字的工具函数
const formatAreaName = (pinyin) => {
  return areaMap[pinyin] || pinyin
}

// 风险等级数字转汉字的工具函数
const formatWarnLevel = (level) => {
  return warnLevelMap[level] || level
}

// 汉字转拼音的工具函数
const getAreaPinyin = (chinese) => {
  return Object.keys(areaMap).find(key => areaMap[key] === chinese) || ''
}

// 汉字转风险等级数字的工具函数
const getWarnLevelNumber = (chinese) => {
  return warnLevelReverseMap[chinese] || chinese
}

// 预警列表数据
const warningList = ref([])
// 加载状态
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 详情抽屉
const detailDrawer = ref(false)
const currentWarning = ref({})

// 新增抽屉
const addDrawer = ref(false)
const formRef = ref(null)

// 编辑抽屉相关
const editDrawer = ref(false)
const editFormRef = ref(null)
const editFormData = reactive({
  id: '',
  area: '',
  date: '',
  warnLevel: '',
  algalBloom: '',
  operationTime: ''
})

// 编辑时，将表格的汉字区域转为拼音赋值给表单，将风险等级汉字转为数字
const handleEdit = (row) => {
  editDrawer.value = true
  // 复制行数据，并将area的汉字转为拼音，warnLevel的汉字转为数字
  Object.assign(editFormData, {
    ...row,
    area: getAreaPinyin(row.area), // 核心转换：汉字→拼音
    warnLevel: getWarnLevelNumber(row.warnLevel) // 核心转换：汉字→数字
  })
}

// 保存更新数据
const handleUpdate = async () => {
  try {
    await editFormRef.value.validate()
    await warningUpdateService(editFormData)
    ElMessage.success('更新成功')
    editDrawer.value = false
    getWarningList()
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('更新失败')
    }
  }
}

// 表单数据
const formData = reactive({
  area: '',
  date: '',
  warnLevel: '',
  algalBloom: '',
  operationTime: ''
})

// 表单验证规则
const rules = {
  area: [{ required: true, message: '请选择区域', trigger: 'change' }],
  date: [{ required: true, message: '请选择预警日期', trigger: 'change' }],
  warnLevel: [{ required: true, message: '请选择风险等级', trigger: 'change' }],
  algalBloom: [{ required: true, message: '请描述水华覆盖比例', trigger: 'blur' }]
}

// 查询表单数据
const queryForm = reactive({
  area: '',
  date: '',
  warnLevel: ''
})

// 获取列表时，将后端返回的拼音area转为汉字，风险等级数字转为汉字
const getWarningList = async (isQuery = false) => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...(isQuery ? queryForm : {})
    }
    const result = await warningListService(params)
    // 遍历列表，将每个item的area拼音转为汉字，warnLevel数字转为汉字
    const formatList = result.data.items.map(item => ({
      ...item,
      area: formatAreaName(item.area), // 拼音→汉字
      warnLevel: formatWarnLevel(item.warnLevel) // 数字→汉字
    }))
    warningList.value = formatList
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('获取预警列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  getWarningList()
})

// 查询操作
const handleQuery = () => {
  currentPage.value = 1
  getWarningList(true)
}

// 重置查询
const resetQuery = () => {
  queryForm.area = ''
  queryForm.date = ''
  queryForm.warnLevel = ''
  currentPage.value = 1
  getWarningList()
}

// 分页事件
const handlePageChange = (page) => {
  currentPage.value = page
  const isQuery = Object.values(queryForm).some(val => val !== '')
  getWarningList(isQuery)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  const isQuery = Object.values(queryForm).some(val => val !== '')
  getWarningList(isQuery)
}

// 查看详情
const handleView = (row) => {
  currentWarning.value = { ...row }
  detailDrawer.value = true
}

// 打开新增抽屉
const openAddDrawer = () => {
  formRef.value?.resetFields()
  addDrawer.value = true
}

// 保存新增数据
const handleSave = async () => {
  try {
    await formRef.value.validate()
    await warningSaveService(formData)
    ElMessage.success('新增成功')
    addDrawer.value = false
    getWarningList()
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('新增失败')
    }
  }
}

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确认删除该预警记录吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await warningDeleteService(row.id)
      ElMessage.success('删除成功')
      getWarningList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}
</script>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.query-form {
  padding: 10px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding-left: 16px;
}
</style>